<template>
  <div class="content">
    <!-- top -->
    <div>
        <van-nav-bar class="nav-bar-style" left-arrow @click-left="onClickLeft">
        <template #title>
            <div class="nav-bar-title-style">移库</div>
        </template>
        <template #left>
            <van-icon size="30" name="arrow-left" color="#FFF" />
        </template>
        </van-nav-bar>
    </div>

    <!-- main -->
    <div class="selectCont">
        <!-- <div class="comdix"  @click="showPickerFun">
            <div class="pickname">储存位置</div>
        </div>
        <div class='pickRight' @click="showPickerFun">
            <span style="margin-right: 10px;color: #999999;">{{names}}</span>
            <van-icon name="arrow" />
        </div> -->

        <div class="comdix"  @click="showSlectStoreLocation">
            <div class="pickname">储存位置</div>
        </div>
        <div class='pickRight' @click="showSlectStoreLocation">
            <span style="margin-right: 10px;color: #999999;">{{this.getLocationText()}}</span>
            <van-icon name="arrow" />
        </div>
    </div>

    <!-- <van-popup v-model="showPicker" round position="bottom">
        <van-picker
            title="请选择"
            show-toolbar
            :columns="columns"
            @confirm="onConfirm"
            @cancel="onCancel"
            />
    </van-popup> -->
    <van-popup v-model="isShowSelectStoreLocation" style="width:100%" position="bottom">
      <div v-show="isShowSelectStoreLocation" class="pickerToobarStyle">
        <div class="pickerToolbarContentButton" @click="isShowSelectStoreLocation = false">取消</div>
        <div v-show="isShowSelectStoreLocation" class="pickerToolbarContent">
          <p>请选择储存位置</p>
        </div>
        <div @click="onClickCustomerConfirm" class="pickerToolbarContentButton">确认</div>
      </div>
      <van-picker
        ref="picker"
        class="pickerToolbarContentButton"
        confirm-button-text="确定"
        cancel-button-text="取消"
        visible-item-count="6"
        :columns="storeDataList"
      ></van-picker>
    </van-popup>

    <!-- 列表 -->
    <ul style="margin-top:20px;">
        <li style="list-style-type:none;" v-for="(item,index) in moveStoreArray" :key="index">
            <van-swipe-cell>
                <div class="totoalItemStyle">
                    <div class="left">
                        <div class="leftLi">
                            <span class="title">物料名称</span>
                            <span class="desc">{{item.materialName}}</span>
                        </div>
                        <div class="leftLi">
                            <span class="title">物料编码</span>
                            <span class="desc">{{item.materialCode}}</span>
                        </div>
                        <div class="leftLi">
                            <span class="title">二维码</span>
                            <span class="desc">{{item.barCode}}</span>
                        </div>
                        <div class="leftLi">
                            <span class="title">原货架</span>
                            <span class="desc">{{item.sourceStorageName}}</span>
                        </div>
                    </div>
                </div>
                <template #right>
                    <van-button square text="删除" type="danger" class="delete-button" @click="del(item,index)"/>
                </template>
            </van-swipe-cell>
        </li>
    </ul>
    <!-- <div @click="scanMoveStorage">测试</div> -->
    <div class="btnCont">
        <button class="btn" :disabled="isBtnToInstorageDisabled" @click="submit" :class="isBtnToInstorageDisabled?'huise':''">提交</button>
    </div>

    <!-- 暂无数据 -->
    <div v-if="moveStoreArray.length == 0" class="noDataCont">
        <div class="imgs">
            <img src="@/assets/img_no-data.png" alt="暂无数据" class="nod" />
        </div>
        <div class="noDataTitle">请选择物料进行扫码</div>
    </div>
  </div>
</template>

<script>
import http from "@/utils/request.js";
import api from "@/utils/api";
import { Dialog } from "vant";
import { mapState } from 'vuex'
import { Toast } from "vant";
export default {
  data() {
    return {
      isBtnToInstorageDisabled:false,
      isShowSelectStoreLocation: false,
      storeDataList:[],
      storeLocationInfo: {
        areaIndex: 0,
        areaValue: "",
        regionIndex: 0,
        regionValue: "",
        shelfIndex: 0,
        shelfValue: "",
        shelfId: ""
      },
      placeHolderInfo: {
        selectLocation: "请选择 储存位置 >"
      },

      names:'切换',
      showPicker:false,
      columns:[],
      moveStoreArray:[],
      obj:{},
      array:[],
      targetStorageId:'',
      targetStorageName:'',

      moveArrays:[],
      showMoveList:[]
    };
  },
  created() {
      this.moveArrays=this.$store.state.user.moveArrays
      console.log(this.moveArrays)
      this.moveArrays.forEach(item =>{
          if(localStorage.getItem('userId') == item.userId){
            this.moveStoreArray = item.moveArrays;
          }
      })
      window.scanMoveStorage = this.scanMoveStorage;
      this.init()
  },
  methods: {
    init(){
        // this.moveStoreArray = this.$store.state.inventory.moveStoreArray1;
        this.getAllStoreInfos()
    },
    // 获取三级联动
    getAllStoreInfos() {
        let param = {};
        http.fetchGet(api.getAllStoreInfos, param).then(res => {
            res.data.forEach(item => {
                item.text = item.storeName;
                if (this.checkHasProp(item, "storeAreas")) {
                    //赋值库区信息
                    item.children = item.storeAreas;
                    item.storeAreas.forEach(regionInfo => {
                        regionInfo.text = regionInfo.areaName;
                        if (this.checkHasProp(regionInfo, "storages")) {
                            regionInfo.children = regionInfo.storages;
                            regionInfo.storages.forEach(shelfInfo => {
                                shelfInfo.text = shelfInfo.storageName;
                            });
                        }
                    });
                }
                this.storeDataList.push(item);
            });
        }).catch(err => {
            console.log(" err  is here " + err);
        });
    },
    showSlectStoreLocation() {
      this.isShowSelectStoreLocation = true;
    },
    isHasSelectLastLocation(currentSelectLocationText) {
      let result = false;
      for (let inStorageInfo of this.inStorageInfos) {
        if (inStorageInfo.storageMappingName == currentSelectLocationText) {
          result = true;
          break;
        }
      }
      return result;
    },
    getLocationText() {
      if (!this.storeLocationInfo.shelfValue) {
        return "请选择储存位置 ";
      } else {
        return (
          this.storeLocationInfo.areaValue +
          "/" +
          this.storeLocationInfo.regionValue +
          "/" +
          this.storeLocationInfo.shelfValue
        )
      }
    },
    onClickCustomerConfirm() {
      let indexes = this.$refs.picker.getIndexes();
      let values = this.$refs.picker.getValues();

      if ((indexes.length < 3) | (values.length < 3)) {
        Toast(" 请选择有货架的库区 去入库");
        return;
      }

      this.storeLocationInfo.areaValue = values[0];
      this.storeLocationInfo.regionValue = values[1];
      this.storeLocationInfo.shelfValue = values[2];

      /*
      storeValues is 仓库1,库区6,货架10
      storeIndexs is 0,0,0
      */

      this.storeLocationInfo.areaIndex = indexes[0];
      this.storeLocationInfo.regionIndex = indexes[1];
      this.storeLocationInfo.shelfIndex = indexes[2];

      console.log("areaIndex 是:" + indexes[0]);
      console.log("regionIndex 是:" + indexes[1]);
      console.log("shelfIndex 是:" + indexes[2]);

      let areaIndex = this.storeLocationInfo.areaIndex;
      let regionIndex = this.storeLocationInfo.regionIndex;
      let shelfIndex = this.storeLocationInfo.shelfIndex;

      let storeArea = this.storeDataList[areaIndex];
      let storeRegionArray = storeArea.children;
      let storeRegion = storeRegionArray[regionIndex];
      let storeShelfArray = storeRegion.children;
      console.log(this.storeLocationInfo.areaValue)
      if (storeShelfArray.length < 1) {
        Toast(" 请选择有货架的库区 去入库");
        return;
      }
      let storeAreadId = storeArea.id;
      let storeRegionId = storeRegion.id;
      let storeShelfId = storeShelfArray[shelfIndex].storageMappingId;
      this.storeLocationInfo.shelfId = storeShelfId;
      console.log("货架ID " + storeShelfId);
      console.log("仓储信息" + this.getLocationText());

      this.isShowSelectStoreLocation = false;
      this.placeHolderInfo.selectLocation = this.getLocationText();

      let currentSelectLocationText = this.getLocationText();

      this.checkBtnToInStorageStatus();
    },
    //扫码
    scanMoveStorage(scanedBarCode){
        // scanedBarCode = '3803480406162931713'
        
        var param={
          code: scanedBarCode,
        };
        http.fetchGet(api.getmoveBarCodeInfo, param, "正在扫码,请稍后...").then(res => {
          if (res.code === 1) {
              this.obj = res.data;

             if(this.getIsDulpicateScanCode(scanedBarCode)){
                  Dialog.alert({
                    title: "友情提示",
                    message: '重复扫码！'
                  });
                  return;
             }else{
                  // item.barCodeArray.push(scanedBarCode)
             }

           
              console.log('----11111111--')
              this.$store.commit('moveArrays',{array:this.moveArrays,flag:2})

              // this.$store.commit("moveStoreArray1", {res:res.data,flag:1});
              // this.moveStoreArray = this.$store.state.inventory.moveStoreArray1;
              this.getUserInforLocal(res.data)
          } else if (res.code === 2){
              Dialog.alert({
                title: "友情提示",
                message: res.message
              });
          }
        }).catch(err => {
            console.log(" catch err  is  " + err);
            Dialog.alert({
              title: "友情提示",
              message: err
            });
        });
        this.checkBtnToInStorageStatus()
    },
    // 切换用户展示不同localStore缓存
    getUserInforLocal(data){
       this.moveArrays.forEach((item,i) =>{
          if(localStorage.getItem('userId') == item.userId){
            item.moveArrays.push(data)
          }
       })
       this.$store.commit('moveArrays',{array:this.moveArrays,flag:2})
       this.moveArrays.forEach((item,i) =>{
          if(localStorage.getItem('userId') == item.userId){
            this.moveStoreArray = item.moveArrays
          }
       })
    },
    //判断是否重复扫码
    getIsDulpicateScanCode(scanedBarCode){
        let result = false;
        this.moveArrays.forEach((item,i) =>{
          if(localStorage.getItem('userId') == item.userId){
             if(item.barCodeArray.indexOf(scanedBarCode) > -1){
                  result= true;
             } else {
                item.barCodeArray.push(scanedBarCode)
                result = false;
             }
          }
        })
        this.$store.commit('moveArrays',{array:this.moveArrays,flag:2})
        return result
        // if(this.$store.state.inventory.array1.indexOf(scanedBarCode) > -1) {
        //     Dialog.alert({
        //         title: "友情提示",
        //         message: '重复扫码！'
        //     });
        //     return false
        // }else{
        //     this.$store.commit("array1", {code:scanedBarCode,flag:1});
        //     return true
        // }
    },
    //删除
    del(row,index){
        // var index1 = null;
        // var index2 = null;
        // for(var i in this.$store.state.inventory.moveStoreArray1){
        //   if(this.$store.state.inventory.moveStoreArray1[i].barCode === row.barCode){
        //     index1 = i
        //   }
        // }
        // for(var j in this.$store.state.inventory.array1){
        //   if(this.$store.state.inventory.array1[j] === row.barCode){
        //     index2 = j
        //   }
        // }
        Dialog.confirm({
            title: '友情提示',
            message: '取消这些物料的移库操作？',
        }).then(() => {
            // this.$store.commit("moveStoreArray1", {res:index1,flag:2});
            // this.$store.commit("array1", {code:index2,flag:2});
            this.moveArrays.forEach((item,i) =>{
              if(localStorage.getItem('userId') == item.userId){
                item.moveArrays.splice(index,1)
                for(var j in item.barCodeArray){
                    if(item.barCodeArray[j] === row.barCode){
                      item.barCodeArray.splice(j,1)
                    }
                }
              }
            })
            this.$store.commit('moveArrays',{array:this.moveArrays,flag:2})
            this.moveArrays.forEach((item,i) =>{
                if(localStorage.getItem('userId') == item.userId){
                  this.moveStoreArray = item.moveArrays
                }
            })
            Toast.success('取消成功');
            this.checkBtnToInStorageStatus()
        }).catch(() => {
            
        });
    },
    //提交
    submit(){
        Dialog.confirm({
            title: '友情提示',
            message: '确定要将这些物料移动到'+ this.getLocationText() +'?',
        }).then(() => {
            let param = {
              targetStorageId: this.storeLocationInfo.shelfId,
              targetStorageName: this.storeLocationInfo.shelfValue,
              movementBarCodes: this.moveStoreArray
            }
            http.fetchPost(api.createMovement, param).then(res => {
                if(res.code === 1){
                  Toast.success('移库成功');
                  // this.$store.commit("moveStoreArray1", {flag:3});
                  // this.$store.commit("array1", {flag:3});
                  this.moveArrays.forEach((item,i) =>{
                    if(localStorage.getItem('userId') == item.userId){
                      item.moveArrays=[];
                      item.barCodeArray=[];
                    }
                  })
                  this.$store.commit('moveArrays',{array:this.moveArrays,flag:2})
                  setTimeout(() => {
                    this.$router.push({
                      path:'/Navagation',
                    });
                    Toast.clear()
                  }, 500);
                }
            }).catch(err => {
                Dialog.alert({
                    title: "友情提示",
                    message: err
                });
            });
        }).catch(() => {
            
        });
    },
    checkBtnToInStorageStatus() {
      let isHasLocation = this.hasSelectLocation();
      var flag = false;
      if(this.$store.state.inventory.array1.length>0){
          flag = true
      }else{
          flag = false
      }
      let isScanedBarcodeLength =  flag

      //没有选择位置 或者没有扫够条码  disableButtonStatus
      // this.isBtnToInstorageDisabled = !isHasLocation || !isScanedBarcodeLength;
      this.isBtnToInstorageDisabled = false
      console.log("重新 调整btn status  ");
    },
    hasSelectLocation() {
      if (this.placeHolderInfo.selectLocation.indexOf("/") > -1) {
        return true;
      } else {
        return false;
      }
    },
    checkHasProp(someItem, propName) {
      if (someItem.hasOwnProperty(propName)) {
        return true;
      } else {
        return false;
      }
    },
    onClickLeft() {
        this.$router.push({
          path:'/Navagation',
        });
    },
    showPickerFun(){
        if(this.showPicker){
          this.showPicker = false;
        }else{
          this.showPicker = true;
        }
    },
    starSeeStore(){

    },
    // onConfirm(value, index){
    //     console.log(value)
    //     console.log(index)
    //     if(value[0]){
            
    //     }
        
    //     if(value[1]){
    //         value[1]= '/' + value[1]
    //     }else{
    //         value[1]= ''
    //     }

    //     if(value[2]){
    //         value[2]= '/' + value[2]
    //     }else{
    //         value[2]=''
    //     }
        
    //     this.names = value[0] + value[1] + value[2]

    //     index[0] = index[0].toString();
    //     index[1] = index[1].toString();
    //     index[2] = index[2].toString();
    //     console.log(this.columns)
    //     for (var i in this.columns) {
    //         if(index[0] === i && this.columns[i].children.length > 0){
    //             for(var j in this.columns[i].children){
    //                 if(index[1] === j && this.columns[i].children[j].children.length <= 0){
    //                     this.targetStorageId = this.columns[i].children[j].areaId;
    //                     this.targetStorageName = this.columns[i].children[j].areaName;

    //                 }else if(index[1] === j && this.columns[i].children[j].children.length > 0){
    //                     for(var k in this.columns[i].children[j].children){
    //                         if(index[2] === k){
    //                             console.log()
    //                             this.targetStorageId = this.columns[i].children[j].children[k].storageMappingId;
    //                             this.targetStorageName = this.columns[i].children[j].children[k].storageName;
    //                         }
    //                     }
    //                 }
    //             }
    //         }
    //     }
    //     console.log(this.targetStorageId)
    //     console.log(this.targetStorageName)
    //     this.showPicker = false;
    // },
    onCancel(){
        this.showPicker = false;
    }
  }
};
</script>
<style scoped lang="scss">
    .content{
        height: 100%;
    }
  .nav-bar-style {
    background: #2E71FF;
    color: #fff;
  }
  .nav-bar-title-style {
    font-size: 22px;
    text-align: center;
    font-family: PingFangSC-Regular;
    color: #fff;
    margin-right: 62px;
  }
  .slot{
    width: 100%;
    height: 15px;
    background-color: #F6F6F6;
  }

//   下拉
.selectCont{
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 8px 20px;
    font-size: 20px;
    height: 40px;
    z-index: 9999;
    position: relative;
  }
  .pickRight{
    display: flex;
    align-items: center;
  }
  .van-popup--top.van-popup--round{
    margin-top: 124px;
  }
  .nav-bar-style{
    z-index: 9999;
  }
  .pickname{
      color: #999999;
  }
//   列表
ul{
    height: 60%;
    overflow: scroll;
}
.totoalItemStyle {
    padding-bottom: 10px;
    box-sizing: border-box;
    border-bottom: 1px solid #e6e6e6;
    display: flex;
    padding: 16px;
    box-sizing: border-box;
    flex-shrink: 1;
    font-size: 20px;
    align-items: flex-start;
    background-color: #fff;
    flex-grow: 1;
    width: 100%;
    justify-content: space-between;
    flex-flow: row nowrap;
    align-items: center;
  }
  .left {
    width: 100%;
    text-align: left;
  }
  .leftLi {
    display: flex;
    line-height: 40px;
    // word-break: keep-all;
    // white-space: nowrap;
  }
  .title {
    min-width: 20%;
    color: #999999;
  }
  .desc {
    margin-left: 20px;
    color: #333333;
  }
  .delete-button{
    height: 100%;
  }
//   按钮
  .btnCont{
      width: 90%;
      margin: 70px auto;
      bottom: 20px;
  }
  .btn{
      border: 0px;
      background: #2E71FF;
      border-radius: 50px;
      color: #fff;
      width: 100%;
      padding: 20px 0px;
  }
  .huise{
    background: #CCCCCC;
  }
  /* 暂无数据 */
.noDataTitle {
  color: #666666;
  font-size: 20px;
  margin-top: 10px;
}
.noDataCont {
  height: 274px;
  /* width: 100%; */
  position: absolute;
  top: 50%;
  left: 50%;
  margin-top: -137px;
  transform: translate(-50%);
}
.nod {
  width: 100%;
  height: 100%;
}





.pickerToobarStyle {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 20px;
  color: #477cec;
}
.pickerToolbarContent {
  display: flex;
  align-items: center;
}
.pickerToolbarContentButton {
  padding-left: 10px;
  padding-right: 10px;
  align-items: center;
}
</style>
